const { ccclass, property } = cc._decorator;

@ccclass
export default class GameCtrl extends cc.Component {

    @property({ type: cc.Node })
    player: cc.Node = null;

    @property({ type: cc.Integer })
    playerOriginAngle: number = 45;

    private playerLastAngle: number = 0;

    @property({ type: cc.Node })
    circle: cc.Node = null;

    @property({ type: cc.Integer, tooltip: '物体弹射速度' })
    speed: number = 20;

    @property({ type: cc.Integer, tooltip: '角速度' })
    angularSpeed: number = 120;

    @property({ type: cc.Integer, tooltip: '重力加速度' })
    gravitySpeed: number = -10;

    // 物体是否在旋转
    isRotating: boolean = true;

    // 物体是否在跳跃
    isJumping: boolean = false;

    jumpingVx: number = 0;

    jumpingVy: number = 0;

    start() {

        this.playerLastAngle = this.playerOriginAngle;

        this.isRotating = true;

        this.adjustObj();

    }

    adjustObj(): void {

        // 物体初始角度
        this.player.angle = this.playerLastAngle - 90;

        // 角度换弧度
        const r = this.playerLastAngle * Math.PI / 180;
        const x = (this.circle.height + this.player.height) * 0.5 * Math.cos(r);
        const y = (this.circle.height + this.player.height) * 0.5 * Math.sin(r);

        // console.log('x: ' + x + ', y: ' + y)

        // 物体初始位置
        this.player.setPosition(this.circle.getPosition().add(new cc.Vec2(x, y)));

    }

    /**
     * 物体跳跃
     */
    jump(): void {
        this.isRotating = false;
        this.isJumping = true;

        const degree = this.player.angle + 90;
        const r = degree * Math.PI / 180;
        console.log('degree: ' + degree);
        this.jumpingVx = this.speed * Math.cos(r);
        this.jumpingVy = this.speed * Math.sin(r);

    }

    update(dt: number) {

        // 中心圆旋转
        this.circle.angle += this.angularSpeed * dt;

        if (this.isRotating) {
            // 玩家跟随中心圆旋转
            this.playerLastAngle += this.angularSpeed * dt;
            // 调整物体位置
            this.adjustObj();
        }

        if (this.isJumping) {
            // 重力修正
            if (this.gravitySpeed > 0) {
                this.gravitySpeed = - this.gravitySpeed;
            }

            // 物体抛物线
            this.player.x += this.jumpingVx * dt;
            this.player.y += this.jumpingVy * dt + 0.5 * this.gravitySpeed * dt * dt;
            this.jumpingVy += this.gravitySpeed * dt;

            // 物体角度修正
            let r = Math.atan2(this.jumpingVy, this.jumpingVx);
            const degree = r * 180 / Math.PI;
            this.player.angle = degree - 90;
        }

    }

}